﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace delegate代理
{
    class Program
    {
        //delegate for a function that receives an int and return a bool
        public delegate bool NumberPredicate(int number);

        static void Main(string[] args)
        {
            int[] nums = { 1, 3, 4, 5, 6, 7, 8, 9 };
            NumberPredicate evenPredicate = IsEven;

            Console.WriteLine("Call IsEven using delegate evenPredicate:{0}\n", evenPredicate(4));

            List<int> evens = FilterNumbers(nums, evenPredicate);
            DisplayList("use IsEven to filter even numbers:", evens);

            evenPredicate = IsOdd;
            List<int> odds = FilterNumbers(nums, evenPredicate);
            DisplayList("use IsOdd to filter odd numbers:", odds);

            //IsOver5 传递给数组的时候隐式地转换为NumberPredicate代理
            List<int> isOver5 = FilterNumbers(nums, IsOver5);
            DisplayList("use IsOver5 to filter numbers over 5:", isOver5);
            Console.ReadKey();
        }//end method Main

        private static bool IsEven(int num)
        {
            return ((num % 2) == 0);
        }//end method IsEven

        private static bool IsOdd(int num)
        {
            return (1 == (num % 2));
        }//end method IsOdd 

        private static bool IsOver5(int num)
        {
            return (num > 5);
        }//end method IsOver5

        private static List<int> FilterNumbers(int[] nums, NumberPredicate predicate)
        {
            List<int> result = new List<int>();

            foreach (int num in nums)
            {
                if (predicate(num))
                {
                    result.Add(num);
                }
            }//end for

            return result;
        }//end method FilterNumbers 

        private static void DisplayList(string header, List<int> results)
        {
            Console.Write(header);
            
            foreach (int item in results)
            {
                Console.Write("  {0}", item);
            }//end for

            Console.WriteLine("\n");
        }//end method DisplayList
    }
}
